package com.imay.live.fragment.discovery;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.util.ViewUtil;
import com.imay.live.IMApplication;
import com.imay.live.R;
import com.imay.live.activity.MainActivity2;
import com.imay.live.activity.RoomLiveShortActivity;
import com.imay.live.activity.WebViewActivity;
import com.imay.live.adapter.DiscoveryIndicatorAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.BannerCache;
import com.imay.live.cache.DiscoveryCache;
import com.imay.live.cache.LabelCache;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.BaseRequestFragment;
import com.imay.live.helper.H5Helper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.DataSetListener;
import com.imay.live.manager.DataSetManager;
import com.imay.live.model.BannerInfoModel;
import com.imay.live.model.DiscoveryColumnHolderModel;
import com.imay.live.model.DiscoveryColumnModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.view.banner.BannerLayout;
import com.imay.live.view.banner.MindleViewPager;
import com.imay.live.view.indicator.Indicator;
import com.imay.live.view.indicator.RecyclerIndicatorView;
import com.imay.live.view.indicator.ScrollIndicatorView;
import com.imay.live.view.indicator.slidebar.ColorBar;
import com.imay.live.view.indicator.transition.OnTransitionTextListener;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chan on 2017/3/25.
 */

public class DiscoveryFragment extends BaseRequestFragment implements DataSetListener {
    private List<LoadFragment> fragmentList;
    private int tabH;//首页TAB的高度
    DiscoveryCache discoveryCache;
    private int select;
    public TwinklingRefreshLayout mRefreshLayout;
    MindleViewPager mindleViewPager;

    private boolean isInstance = true;
    private DataSetManager mDataSetManager;
    private String loadColumnsConmand;
    private RecyclerIndicatorView mIndicatorView;
    private ScrollIndicatorView siv_discovery;

    public static DiscoveryFragment newInstance() {
        return new DiscoveryFragment();
    }

    public void setTabH(int tabH) {
        this.tabH = tabH;
        if (mRefreshLayout != null) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mRefreshLayout.getLayoutParams();
            params.bottomMargin = tabH;
            mRefreshLayout.setLayoutParams(params);
        }
//        if (fragmentList != null) {
//            fragmentList.get(0).setTabH(tabH);
//        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_discovery;
    }

    private void addFragment(LoadFragment loadFragment) {

        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(loadFragment.getClass().toString());
        if (fragment == null) {
            transaction.add(R.id.fragment_id, loadFragment, loadFragment.getClass().toString());
        }
        loadFragment.setRefreshLayout(getActivity(), mRefreshLayout);
        loadFragment.setUserVisibleHint(true);
        hideFragment(transaction, loadFragment);
        transaction.show(loadFragment);
        transaction.commitAllowingStateLoss();
        loadFragment.setTabH(tabH);
    }

    //隐藏所有的fragment
    private void hideFragment(FragmentTransaction transaction, LoadFragment loadFragment) {
        for (LoadFragment fragment : fragmentList) {
            if (fragment == loadFragment) {
                continue;
            }
            fragment.setUserVisibleHint(false);
            transaction.hide(fragment);
        }
    }

    public static int getviewHeight() {
        float w = ViewUtil.mScreemWidth * MindleViewPager.VIEW_SCALE * MindleViewPager.MAX_SCALE;
        float p = IMApplication.getInstance().getResources().getDimension(R.dimen.banner_space) * 2 + BannerLayout.getshawH();
        return (int) (((w * 128) / 328) + p);
    }

    private void addbanner(MindleViewPager mindleViewPager) {
        final float scale = getResources().getDisplayMetrics().density;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (167 * scale + 0.5f));
        mindleViewPager.setLayoutParams(layoutParams);
        mRefreshLayout.setTitle(mindleViewPager);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mIndicatorView = $(R.id.riv_discovery);
        siv_discovery = $(R.id.siv_discovery);
        mRefreshLayout = $(R.id.refresh);
        mindleViewPager = $(R.id.bannerview);
        addbanner(mindleViewPager);
//
        $(R.id.iv_new_chanllen_discovery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoomLiveShortActivity.startActivity(getActivity());
                MobclickAgent.onEvent(getActivity(), "zuixin_click");
            }
        });
        loadColumns();
    }

    private void goWebBanner(BannerInfoModel bannerInfoModel) {
        if (bannerInfoModel == null || TextUtils.isEmpty(bannerInfoModel.getAdUrl())) {
            return;
        }
        MobclickAgent.onEvent(getActivity(), "find_click_banner");
        if (bannerInfoModel.getAdUrl().startsWith("type=")) {
            String stringBuilder = "imay://com.imay.live/openwith?" +
                    bannerInfoModel.getAdUrl();
            H5Helper.startActivity(stringBuilder, getActivity());
        } else if (bannerInfoModel.getAdUrl().startsWith("imay://com.imay.live/openwith?")) {
            H5Helper.startActivity(bannerInfoModel.getAdUrl(), getActivity());
        } else {
            UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
            if (userInfoModel != null) {
                UserModel userModel = userInfoModel.getUser();
                if (userModel != null) {
                    long uid = userModel.getUid();
                    String url = bannerInfoModel.getAdUrl();
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(url);
                    if (url.indexOf("?", 0) > -1) {
                        stringBuilder.append("&");
                    } else {
                        stringBuilder.append("?");
                    }
                    stringBuilder.append("uid=");
                    stringBuilder.append(uid);
                    if (AccountManager.getInstance().getToken() != null && !TextUtils.isEmpty(AccountManager.getInstance().getToken().accessCode)) {
                        stringBuilder.append("&accessToken=");
                        stringBuilder.append(AccountManager.getInstance().getToken().accessCode);
                    }
                    WebViewActivity.startActivity(getActivity(), bannerInfoModel.getAdName(), stringBuilder.toString());
                }
            }
        }

    }

    public void scrollTop() {
        if (mRefreshLayout != null && mRefreshLayout.getChildView() instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) mRefreshLayout.getChildView();
            if (recyclerView.getChildCount() == 0) {
                return;
            }
            float y = recyclerView.getChildAt(0).getY();
            if (y < -10 || y >= 0) {
                ((RecyclerView) mRefreshLayout.getChildView()).smoothScrollToPosition(0);
                mRefreshLayout.startRefresh();
                return;
            }
//            if (istop) {
            ((RecyclerView) mRefreshLayout.getChildView()).smoothScrollToPosition(0);
            mRefreshLayout.setOnScrollListener(new TwinklingRefreshLayout.OnScrollListener() {
                @Override
                public void onScrolled(int firstVisibleItem) {
                    if (firstVisibleItem == 0) {
                        mRefreshLayout.startRefresh();
                        mRefreshLayout.setOnScrollListener(null);
                    }
                }
            });
            mRefreshLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_MOVE) {
                        mRefreshLayout.setOnScrollListener(null);
                    }
                    return false;
                }
            });
//            }
        }
    }

    public void reloadData(final boolean refresh) {
        ThreadManager.execute(new Runnable() {
            @Override
            public void run() {
                BannerCache bannerCache = new BannerCache(new BannerCache.BannerListener() {
                    @Override
                    public void onRequestSuccess(final ArrayList<BannerInfoModel> bannerInfoModelArrayList) {
                        ThreadManager.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mindleViewPager == null) {
                                    return;
                                }
                                mindleViewPager.setAdapter(new MindleViewPager.LunAdapter() {
                                    @Override
                                    public View getview(ViewGroup container, final int position) {
                                        BannerLayout linearLayout = new BannerLayout(container.getContext(), mindleViewPager.getViewPager().getLayoutParams().height);
                                        GlideUtil.loadRectangleImage(linearLayout.getImageView(), bannerInfoModelArrayList.get(position).getAdFile(), R.dimen.size_8dp, R.drawable.shape_placeholder);
                                        linearLayout.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                goWebBanner(bannerInfoModelArrayList.get(position));
                                            }
                                        });
                                        return linearLayout;
                                    }
                                }, bannerInfoModelArrayList, R.mipmap.ico_02lunbo, R.mipmap.ico_02zibo);
                            }
                        });
                    }
                });
                bannerCache.getCache(refresh);
                /*new PastePhotoCache(new PastePhotoCache.PastePhotoListener() {
                    @Override
                    public void onRequestSuccess(final ArrayList<FeedModel> feedsBeanArrayList) {
                        ThreadManager.post(new Runnable() {
                            @Override
                            public void run() {
                                if (!fragmentList.isEmpty()) {
                                    if (getActivity() instanceof MainActivity2) {
                                        if (((MainActivity2) getActivity()).isDestroyed()) {
                                            return;
                                        }
                                    }
                                    for (LoadFragment fragment : fragmentList) {
                                        fragment.updateFeedSuggest(feedsBeanArrayList);
                                    }
                                }
                            }
                        });
                    }
                }).getCache(refresh);*/

                new LabelCache(new LabelCache.LabelListener() {
                    @Override
                    public void onRequestSuccess(final ArrayList<String> labels) {
                        ThreadManager.post(new Runnable() {
                            @Override
                            public void run() {
                                if (fragmentList != null && !fragmentList.isEmpty()) {
                                    if (getActivity() instanceof MainActivity2) {
                                        if (((MainActivity2) getActivity()).isDestroyed()) {
                                            return;
                                        }
                                    }
                                    for (LoadFragment fragment : fragmentList) {
                                        fragment.updateLabels(labels);
                                    }
                                }
                            }
                        });
                    }
                }).getCache(refresh);
            }
        });
    }


    public void reloadData(final LoadFragment fragment, final int refresh) {
        ThreadManager.execute(new Runnable() {
            @Override
            public void run() {
                if (discoveryCache == null) {
                    discoveryCache = new DiscoveryCache();
                }
                if (fragment instanceof HotFragment) {
                    discoveryCache.getHotData(new DiscoveryCache.CallBack() {
                        @Override
                        public void onRequestSuccess(final String command, final String data) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestSuccess(command, data);
                                }
                            });
                        }

                        @Override
                        public void onRequestError(final String command, final int code, final String message) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestError(command, code, message);
                                }
                            });

                        }

                    }, refresh);
//                    reloadData(true);
                }
                if (fragment instanceof SupperFragment) {
                    discoveryCache.getSupperData(new DiscoveryCache.CallBack() {
                        @Override
                        public void onRequestSuccess(final String command, final String data) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestSuccess(command, data);
                                }
                            });
                        }

                        @Override
                        public void onRequestError(final String command, final int code, final String message) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestError(command, code, message);
                                }
                            });

                        }

                    }, refresh);
//                    discoveryCache.getSupperStatData(new DiscoveryCache.CallBack() {
//                        @Override
//                        public void onRequestSuccess(final String command, final String data) {
//                            ThreadManager.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    ((SupperFragment) fragment).onStatSuccess(command, data);
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onRequestError(final String command, final int code, final String message) {
//                            ThreadManager.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    ((SupperFragment) fragment).onStatError(command, code, message);
//                                }
//                            });
//
//                        }
//
//                    }, refresh);
                } else if (fragment instanceof DisCoveryAssortFragment) {
                    discoveryCache.getAssortData(new DiscoveryCache.CallBack() {
                        @Override
                        public void onRequestSuccess(final String command, final String data) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestSuccess(command, data);
                                }
                            });
                        }

                        @Override
                        public void onRequestError(final String command, final int code, final String message) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestError(command, code, message);
                                }
                            });

                        }

                    }, refresh);
                } else if (fragment instanceof CelebrityFragment) {
                    discoveryCache.getCelebrityData(new DiscoveryCache.CallBack() {
                        @Override
                        public void onRequestSuccess(final String command, final String data) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestSuccess(command, data);
                                }
                            });
                        }

                        @Override
                        public void onRequestError(final String command, final int code, final String message) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestError(command, code, message);
                                }
                            });

                        }

                    }, refresh);
                } else if (fragment instanceof GameFragment) {
                    discoveryCache.getGameData(new DiscoveryCache.CallBack() {
                        @Override
                        public void onRequestSuccess(final String command, final String data) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestSuccess(command, data);
                                }
                            });
                        }

                        @Override
                        public void onRequestError(final String command, final int code, final String message) {
                            ThreadManager.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragment.onRequestError(command, code, message);
                                }
                            });

                        }

                    }, refresh);
                }else if (fragment instanceof NormalFragment){
                    fragment.onRefresh();
                }


            }
        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isVisibleToUser) {
            if (fragmentList != null) {
                for (LoadFragment fragment : fragmentList) {
                    if (fragment.isVisible()) {
                        fragment.onResume();
                        break;
                    }
                }
            }
            MobclickAgent.onPageStart(getClass().getSimpleName());
        } else {
            MobclickAgent.onPageEnd(getClass().getSimpleName());
            if (fragmentList != null && fragmentList.size() > 1) {
                if (fragmentList.get(1).isVisible())
                    fragmentList.get(1).setVisibleHint(isVisibleToUser);
            }
        }
    }

    @Override
    public void loadData() {
        if (isCreate) {
            if (AccountManager.getInstance().isLogined()) {
                if (isInstance) {
                    isInstance = false;
                    reloadData(false);
                }
            }
        }
    }

    @Override
    public void clearData() {
        isInstance = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDataSetManager != null) {
            mDataSetManager.unregisterDataNotify();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DisCoveryAssortFragment.REQUE_REFRSH_TITLE) {
            new LabelCache(new LabelCache.LabelListener() {
                @Override
                public void onRequestSuccess(final ArrayList<String> labels) {
                    ThreadManager.post(new Runnable() {
                        @Override
                        public void run() {
                            if (fragmentList != null && !fragmentList.isEmpty()) {
                                if (getActivity() instanceof MainActivity2) {
                                    if (((MainActivity2) getActivity()).isDestroyed()) {
                                        return;
                                    }
                                }
                                for (LoadFragment fragment : fragmentList) {
                                    fragment.updateLabels(labels);
                                }
                            }
                        }
                    });
                }
            }).getCache(true);
        }
    }

    private void loadColumns(){
        loadColumnsConmand = ProtoRequestHelper.task(ProtoHttpFactory.getColumns()).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        ImayLogUtil.log(data);
        if (command.equals(loadColumnsConmand)){
            Result<DiscoveryColumnHolderModel> result = JSON.parseObject(data,new TypeReference<Result<DiscoveryColumnHolderModel>>(){}.getType());
            bindFragmentIndicator(result.data.getColumns());
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        ImayLogUtil.log(message);
        bindFragmentIndicator(null);

    }

    private void bindFragmentIndicator(List<DiscoveryColumnModel> columnModels) {
        String[] tabTitles = new String[]{getString(R.string.str_discovery_hot), getString(R.string.str_discovery_supper), getString(R.string.str_discovery_star), getString(R.string.str_discovery_game)};
        fragmentList = new ArrayList<>();
        if (columnModels!=null && !columnModels.isEmpty()){
            List<String> tabTitleList = new ArrayList<>(columnModels.size());
            for (DiscoveryColumnModel model:columnModels) {
                tabTitleList.add(model.getColumnName());
                if (model.isLive()){
                    fragmentList.add(HotFragment.newInstance());
                }else if (model.isBigka()){
                    fragmentList.add(CelebrityFragment.newInstance());
                }else if(model.isSuperlive()){
                    fragmentList.add(SupperFragment.newInstance());
                }else if (model.isAllKind()){
                    fragmentList.add(NormalFragment.newInstance(model.getColumnName(),model.getColumnSubName()));
                }else{
                    fragmentList.add(GameFragment.newInstance());
                }
            }
            tabTitles =  tabTitleList.toArray(new String[tabTitleList.size()]);
        }else{
            fragmentList.add(HotFragment.newInstance());
            fragmentList.add(SupperFragment.newInstance());
            fragmentList.add(CelebrityFragment.newInstance());
            fragmentList.add(GameFragment.newInstance());
        }
        addFragment(fragmentList.get(0));
        ColorBar colorBar = new ColorBar(getActivity(), getResources().getColor(R.color.tab_ind_color), (int) getResources().getDimension(R.dimen.size_3dp));
        colorBar.setWidth((int) getResources().getDimension(R.dimen.tab_ind_w));
        DiscoveryIndicatorAdapter mIndicatorAdapter = new DiscoveryIndicatorAdapter(getActivity(), getChildFragmentManager(), tabTitles, R.layout.view_indicator_discovery);
        if (fragmentList.size()>4){
            mIndicatorView.setVisibility(View.VISIBLE);
            mIndicatorView.setScrollBar(colorBar);
            mIndicatorView.addItemDecoration(android.R.color.transparent,R.dimen.size_60dp);
            mIndicatorView.setOnTransitionListener(new OnTransitionTextListener().setColorId(getContext(), android.R.color.transparent, android.R.color.transparent));
            mIndicatorView.setAdapter(mIndicatorAdapter.getIndicatorAdapter());
            mIndicatorView.setOnItemSelectListener(new IndicatorSelectedListener());
        }else{
            siv_discovery.setVisibility(View.VISIBLE);
            siv_discovery.setScrollBar(colorBar);
            siv_discovery.setAdapter(mIndicatorAdapter.getIndicatorAdapter());
            siv_discovery.setOnItemSelectListener(new IndicatorSelectedListener());

        }
        reloadData(false);
        mDataSetManager = DataSetManager.Builder.create(this).build();
    }

    class IndicatorSelectedListener implements Indicator.OnItemSelectedListener{

        @Override
        public void onItemSelected(View selectItemView, int select, int preSelect) {
            if (select == 0) {
                MobclickAgent.onEvent(getActivity(), "find_click_hot");
            } else if (select == 1) {
                MobclickAgent.onEvent(getActivity(), "chaodan_open");
            } else if (select == 2) {
                MobclickAgent.onEvent(getActivity(), "find_click_classify");
            } else if (select == 3) {
                MobclickAgent.onEvent(getActivity(), "find_click_game");
            }
            DiscoveryFragment.this.select = select;
            addFragment(fragmentList.get(select));
            if (fragmentList.get(select).isAdded()) {
                fragmentList.get(select).onResume();
            }
            if (preSelect == 1) {
                fragmentList.get(1).setVisibleHint(false);
            } else if (select == 1) {
                fragmentList.get(1).setVisibleHint(true);
            }

        }
        }


}
